package com.kexio.user.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kexio.auth.annotation.RequiresPermission;
import com.kexio.auth.cache.CacheInvalidationService;
import com.kexio.auth.util.AuthContextUtils;
import com.kexio.common.dto.Result;
import com.kexio.user.service.PermissionService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 缓存管理控制器
 * 
 * 🎯 主要功能：
 * 1. 手动清空各类缓存（权限、菜单、字典等）
 * 2. 批量刷新用户权限
 * 3. 缓存状态监控
 * 
 * 🔒 权限要求：
 * - system:cache:* 系列权限
 * - 仅超级管理员可用
 * 
 * @author Kexio Team
 * @since 2.2.0
 */
@RestController
@RequestMapping("/system/cache")
@Tag(name = "缓存管理", description = "系统缓存管理和维护接口")
public class CacheManagementController {
    
    private static final Logger logger = LoggerFactory.getLogger(CacheManagementController.class);
    
    @Autowired
    private CacheInvalidationService cacheInvalidationService;
    
    @Autowired
    private PermissionService permissionService;
    
    /**
     * 🗑️ 清空所有权限相关缓存
     * 
     * 适用场景：直接在数据库插入权限、角色、菜单数据后
     */
    @DeleteMapping("/permissions")
    @RequiresPermission("system:cache:clear")
    @Operation(summary = "清空权限缓存", description = "清空所有权限、角色、菜单相关的缓存")
    public Result<Map<String, Object>> clearPermissionCaches() {
        logger.info("🗑️ 开始清空权限相关缓存");
        String tenantId = AuthContextUtils.getCurrentTenantId();
        
        // 清空权限相关的所有缓存
        cacheInvalidationService.clearAllPermissionRelatedCaches(tenantId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "权限相关缓存已清空");
        result.put("tenantId", tenantId);
        result.put("timestamp", System.currentTimeMillis());
        result.put("cacheTypes", new String[]{"permissions", "roles", "userMenus", "userPermissions"});
        
        logger.info("✅ 权限相关缓存清空完成: tenantId={}", tenantId);
        return Result.success("权限缓存清空成功", result);
    }
    
    /**
     * 🗑️ 清空所有菜单相关缓存
     */
    @DeleteMapping("/menus")
    @RequiresPermission("system:cache:clear")
    @Operation(summary = "清空菜单缓存", description = "清空所有菜单、菜单树相关的缓存")
    public Result<Map<String, Object>> clearMenuCaches() {
        logger.info("🗑️ 开始清空菜单相关缓存");
        String tenantId = AuthContextUtils.getCurrentTenantId();
        
        // 清空菜单相关的所有缓存
        cacheInvalidationService.clearAllMenuRelatedCaches(tenantId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "菜单相关缓存已清空");
        result.put("tenantId", tenantId);
        result.put("timestamp", System.currentTimeMillis());
        result.put("cacheTypes", new String[]{"menus", "menuTree", "userMenus"});
        
        logger.info("✅ 菜单相关缓存清空完成: tenantId={}", tenantId);
        return Result.success("菜单缓存清空成功", result);
    }
    
    /**
     * 🗑️ 清空字典缓存
     */
    @DeleteMapping("/dicts")
    @RequiresPermission("system:cache:clear")
    @Operation(summary = "清空字典缓存", description = "清空所有数据字典相关的缓存")
    public Result<Map<String, Object>> clearDictCaches() {
        logger.info("🗑️ 开始清空字典相关缓存");
        
        // 清空字典缓存
        cacheInvalidationService.clearDictCaches();
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "字典相关缓存已清空");
        result.put("timestamp", System.currentTimeMillis());
        result.put("cacheTypes", new String[]{"dict:items", "dict:label", "dict:batch"});
        
        logger.info("✅ 字典相关缓存清空完成");
        return Result.success("字典缓存清空成功", result);
    }
    
    /**
     * 💥 清空所有缓存（慎用！）
     */
    @DeleteMapping("/all")
    @RequiresPermission("system:cache:clear-all")
    @Operation(summary = "清空所有缓存", description = "清空系统中的所有缓存，慎用！")
    public Result<Map<String, Object>> clearAllCaches() {
        logger.warn("💥 开始清空所有系统缓存");
        String tenantId = AuthContextUtils.getCurrentTenantId();
        
        // 清空各类缓存
        cacheInvalidationService.clearAllPermissionRelatedCaches(tenantId);
        cacheInvalidationService.clearAllMenuRelatedCaches(tenantId);
        cacheInvalidationService.clearDictCaches();
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "所有缓存已清空");
        result.put("tenantId", tenantId);
        result.put("timestamp", System.currentTimeMillis());
        result.put("cacheTypes", new String[]{
            "权限缓存", "角色缓存", "菜单缓存", "字典缓存", "用户权限缓存"
        });
        result.put("warning", "所有缓存已清空，系统性能可能短暂受影响");
        
        logger.warn("✅ 所有系统缓存清空完成: tenantId={}", tenantId);
        return Result.success("所有缓存清空成功", result);
    }
    
    /**
     * 🔄 刷新租户所有用户权限
     * 
     * 适用场景：批量权限变更后，让所有用户重新获取权限
     */
    @PostMapping("/refresh-tenant-permissions")
    @RequiresPermission("system:cache:refresh")
    @Operation(summary = "刷新租户权限", description = "刷新当前租户所有用户的权限缓存")
    public Result<Map<String, Object>> refreshTenantPermissions() {
        logger.info("🔄 开始刷新租户权限");
        String tenantId = AuthContextUtils.getCurrentTenantId();
        
        // 刷新租户权限缓存
        cacheInvalidationService.clearAllPermissionRelatedCaches(tenantId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "租户权限已刷新");
        result.put("tenantId", tenantId);
        result.put("timestamp", System.currentTimeMillis());
        
        logger.info("✅ 租户权限刷新完成: tenantId={}", tenantId);
        return Result.success("租户权限刷新成功", result);
    }
    
    /**
     * 📊 获取缓存状态信息
     */
    @GetMapping("/status")
    @RequiresPermission("system:cache:view")
    @Operation(summary = "查看缓存状态", description = "查看系统缓存的状态信息")
    public Result<Map<String, Object>> getCacheStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("timestamp", System.currentTimeMillis());
        status.put("tenantId", AuthContextUtils.getCurrentTenantId());
        status.put("cacheTypes", new String[]{
            "权限缓存", "角色缓存", "菜单缓存", "字典缓存", "用户权限缓存"
        });
        status.put("supportedOperations", new String[]{
            "清空权限缓存", "清空菜单缓存", "清空字典缓存", "清空所有缓存", "刷新租户权限"
        });
        
        return Result.success("缓存状态获取成功", status);
    }
}
